import { IncomingMessage } from 'http';
import * as http from 'http';
import * as https from 'https';

// 定义HttpClient类型
type HttpClient = typeof http | typeof https;

// 使用更具体的类型来定义data参数，例如：type Data = { /* 数据结构 */ };
export async function sendHttp(data: any, url: string): Promise<any> {
    return new Promise((resolve, reject) => {
        const parsedUrl = new URL(url);
        const httpClient: HttpClient = parsedUrl.protocol === 'https:' ? https : http;
        const requestData = JSON.stringify(data);
        const requestOptions = {
            method: 'POST',
            hostname: parsedUrl.hostname,
            port: parsedUrl.port,
            path: parsedUrl.pathname + parsedUrl.search,
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
                'Content-Length': requestData.length
            }
        };

        const req = httpClient.request(requestOptions, (res: IncomingMessage) => {
            let responseBody = '';
            res.on('data', (chunk) => {
                responseBody += chunk;
            });
            res.on('end', () => {
                if (res.statusCode === 200) {
                    try {
                        const result = JSON.parse(responseBody);
                        resolve(result);
                    } catch (error) {
                        reject(new Error(`Failed to parse JSON response from ${url}: ${error}`));
                    }
                } else {
                    reject(new Error(`Request to ${url} failed with status code ${res.statusCode}`));
                }
            });
        });

        req.on('error', (error) => {
            reject(new Error(`Request to ${url} failed: ${error}`));
        });
        req.write(requestData);
        req.end();
    });
}

export async function getImageAsBase64(url: string, need_base64_header: boolean = true): Promise<string> {
    return new Promise((resolve, reject) => {
        const client: HttpClient = url.startsWith('https') ? https : http;
        client.get(url, (res: IncomingMessage) => {
            if (res.statusCode !== 200) {
                return reject(new Error(`请求失败，状态码：${res.statusCode}`));
            }
            const chunks: Buffer[] = [];
            res.on('data', (chunk: Buffer) => {
                chunks.push(chunk);
            });
            res.on('end', () => {
                const buffer = Buffer.concat(chunks);
                const base64Data = buffer.toString('base64');
                // 安全地获取content-type并转换为base64格式的图片数据
                const mimeType = res.headers['content-type'] ? String(res.headers['content-type']) : 'application/octet-stream';
                const base64Image = need_base64_header ? `data:${mimeType};base64,${base64Data}` : base64Data;
                resolve(base64Image);
            });
        }).on('error', (err: Error) => {
            reject(err);
        });
    });
}
